package com.xiaoye.digitaltwin.filter;

import com.alibaba.fastjson2.JSON;
import com.xiaoye.digitaltwin.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *检查用户是否登录
 * Create by xiaoye on 2023/3/29
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求uri
        String requestURI = request.getRequestURI();

        //不需要拦截的请求
        String[] urls = new String[]{
                "/*",
                "/**",
                "/administrator/login",
                "/student/login",
                "/administrator/logout",
                "/student/logout"
        };

        //判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //放行请求
        if(check){
            filterChain.doFilter(request,response);
            return;
        }

        //针对管理员的登录判断  管理员已登录
        if(request.getSession().getAttribute("administratorId") != null){
            filterChain.doFilter(request,response);
            return;
        }

        //针对学生的登录判断  学生已登录
        if(request.getSession().getAttribute("studentId") != null){
            filterChain.doFilter(request,response);
            return;
        }

        //未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 检查请求是否需要放行  放行为true,要被拦截为false
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
